package registry

import (
	"github.com/go-kratos/kratos/v2/registry"
)

var (
	instance IRegistry
)

func Install(cfg *Config) (IRegistry, error) {
	registrar, err := initRegistry(cfg)
	if err != nil {
		return nil, err
	}

	discovery, err := initDiscovery(cfg)
	if err != nil {
		return nil, err
	}
	instance = New(
		NewRegistrySet(registrar),
		NewDiscoverySet(discovery),
	)

	return instance, nil
}

func initRegistry(cfg *Config) (registry.Registrar, error) {
	fac, err := GetRegistry(cfg.Engine)
	if err != nil {
		return nil, err
	}

	registrar, err := fac(*cfg)
	if err != nil {
		return nil, err
	}

	return registrar, nil
}

func initDiscovery(cfg *Config) (registry.Discovery, error) {
	fac, err := GetDiscovery(cfg.Engine)
	if err != nil {
		return nil, err
	}

	discovery, err := fac(*cfg)
	if err != nil {
		return nil, err
	}

	return discovery, nil
}
